'''
Created on 10.10.2012

@author: doleynik
'''
import webapp2
import json
import time

from webapp2_extras.i18n import gettext as _

from google.appengine.api import users
from apnetmodels.basicmodels import immeuble, lot_budget_weights
from common import functions

from wtforms.ext.appengine.db import model_form
from wtforms.fields import TextField
from wtforms import validators

from BaseHandler import BaseHandler

class Tantieme(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(Tantieme, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.fields = {
                       'lot': _('Lot'), 'lot_detail': _('Lot detail'), 'charges_key': _('Charges key'),
                       'charges_key_name': _('Charges key name'), 'tantieme': _('Tantieme')
                       }
    
    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)
    
    def op_list(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        template_values = {
                           'title': _('Charges keys distribution'),
                           'header': _('%(name)s. Charges keys distribution', name=imm.name),
                           'immeuble': imm,
                           'app_user': self.au,
                           'lurl': users.create_logout_url('/'),
                           'section': 'creation',
                           'leftmenu': 'charges_keys',
                           'fields': self.fields
                           }
        
        template = self.jinja2.get_template('templates/tantieme_list.html')
        self.response.out.write(template.render(template_values))
    
    def op_sum_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return

        s = imm.get_summary_charges_key()        
        o = s.keys()
        o.sort()
        sa = []
        for i in o:
            sa.append((i, s[i]['sum'], s[i]['total']))
        
        ret = {}
        ret['aaData'] = sa
        self.response.out.write(json.dumps(ret))
        
    
    def op_list_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        ta = []
        for l in imm.lot_set.order('batiment').order('number').run():
            for t in l.lotsckeys.order('charges_key').run():
                lot_detail = "%s, %s, %s" % (t.lot.lot_type.name, t.lot.etage, t.lot.surface)
                ta.append([ t.lot.number, unicode(lot_detail), unicode(t.charges_key), unicode(t.tantieme), str(t.key())])
        
        ret = {}
        ret['aaData'] = ta
        self.response.out.write(json.dumps(ret))
        
    def op_add(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        ok_message = ''
        TForm = model_form(lot_budget_weights, exclude=['lastchange_by', 'immeuble'])
        setattr(TForm, 'lot', TextField(u'Lot', [validators.required(),]))
        setattr(TForm, 'charges_key', TextField(u'Charges key', [validators.required(),]))
        TForm.lot.creation_counter = 1
        TForm.charges_key.creation_counter = 2
        TForm.tantieme.creation_counter = 3
        
        if self.request.method == 'GET':
            form = TForm()
        
        if self.request.method == 'POST':
            post_obj = self.request.POST
            
            lots_list = imm.lot_set.order('number')
            exists = False
            for l in lots_list:
                if str(l) == post_obj['lot']:
                    post_obj['lot'] = l
                    exists = True
                    break
            if exists is False:
                post_obj['lot'] = ''
            
            ck_list = imm.get_charges_key_list()
            exists = False
            for c in ck_list:
                if str(c) == post_obj['charges_key']:
                    post_obj['charges_key'] = c
                    exists = True
                    break
            if exists is False:
                post_obj['charges_key'] = ''
            
            form = TForm(post_obj)
            if form.validate():
                new_budget_weight = lot_budget_weights(key_name = form['charges_key'].data.code + '_' + str(form['lot'].data.number) + '_' + str(imm.key().id()),
                                                       lot = form['lot'].data,
                                                       charges_key = form['charges_key'].data, 
                                                       tantieme = form['tantieme'].data,
                                                       lastchange_by = self.au) 
                new_budget_weight.put()
                while not new_budget_weight.is_saved():
                    time.sleep(2)
                ok_message = _('Lot weight was added.')
        
        template_values = {
                           'form': form,
                           'ok_message': ok_message,
                           'fields': self.fields
                           }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    def op_edit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        t_id = kwargs.get('t_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        ok_message = ''
        edit_tantieme = lot_budget_weights.get(t_id)
        
        TForm = model_form(lot_budget_weights, exclude=['lastchange_by', 'immeuble'])
        setattr(TForm, 'lot', TextField(u'Lot', [validators.required(),]))
        setattr(TForm, 'charges_key', TextField(u'Charges key',[validators.required(),]))
        TForm.lot.creation_counter = 1
        TForm.charges_key.creation_counter = 2
        TForm.tantieme.creation_counter = 3
        
        if self.request.method == 'GET':
            form = TForm(obj=edit_tantieme)
        
        if self.request.method == 'POST':
            post_obj = self.request.POST
            
            lots_list = imm.lot_set.order('number')
            exists = False
            for l in lots_list:
                if str(l) == post_obj['lot']:
                    post_obj['lot'] = l
                    exists = True
                    break
            if exists is False:
                post_obj['lot'] = ''
            
            ck_list = imm.get_charges_key_list()
            exists = False
            for c in ck_list:
                if str(c) == post_obj['charges_key']:
                    post_obj['charges_key'] = c
                    exists = True
                    break
            if exists is False:
                post_obj['charges_key'] = ''
            
            form = TForm(post_obj)
            if form.validate():
                form.populate_obj(edit_tantieme)
                edit_tantieme.put()
                ok_message = _('Tantieme was updated.')
        
        template_values = {
                           'form': form,
                           'ok_message': ok_message,
                           'fields': self.fields
                           }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
